package com.loy;

import com.loy.entity.HelloProto;
import com.loy.entity.HelloServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.util.concurrent.TimeUnit;

/**
 * 6. 双向rpc
 */
public class GrpcClient6 {

    public static void main(String[] args) {
        // 1. 创建和服务器端进行通信的管道
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 9000).usePlaintext().build();

        try{

            HelloServiceGrpc.HelloServiceStub helloServiceStub = HelloServiceGrpc.newStub(managedChannel);

            // 监控响应数据
            // 客户端每发送一条消息到服务器端之后，服务器端（1）可以处理完一条就返回，（2）也可以额昂服务器端处理完客户端所有的发送数据之后返回
            StreamObserver<HelloProto.HelloRequest> helloRequestStreamObserver = helloServiceStub.cs2ss(new StreamObserver<HelloProto.HelloResponse>() {
                @Override
                public void onNext(HelloProto.HelloResponse helloResponse) {
                    System.out.println("客户端接收到服务求端的数据：" + helloResponse.getResult());
                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onCompleted() {
                    System.out.println("响应全部结束........");
                }
            });


            // 构建要发送的消息
            for (int i = 0; i < 9; i++) {
                // 构建消息
                HelloProto.HelloRequest.Builder builder = HelloProto.HelloRequest.newBuilder();
                builder.setName("sunshuai : " + i);
                HelloProto.HelloRequest request = builder.build();
                // 将消息发送给服务器端
                helloRequestStreamObserver.onNext(request);
            }

            helloRequestStreamObserver.onCompleted();


            managedChannel.awaitTermination(20,TimeUnit.SECONDS);

        }catch (Exception e){

        }finally {
            managedChannel.shutdown();
        }



    }
}
